package com.dzsw.netty.basic.bytebuf;

import io.netty.buffer.ByteBuf;
import io.netty.buffer.ByteBufAllocator;
import io.netty.buffer.PooledByteBufAllocator;
import io.netty.util.ReferenceCountUtil;
import io.netty.util.ResourceLeakDetector;

public class Bytebuf {

    public static void main(String[] args) {
        byteBufIndexTest();
//        oofTest();
    }

    public static void byteBufIndexTest() {
        ByteBuf byteBuf = ByteBufAllocator.DEFAULT.buffer(16);
        byteBuf.writeInt(127); // int 4字节
        byteBuf.writeInt(128);
        byteBuf.writeInt(129);
        byteBuf.writeInt(130);
        System.out.println(String.format("ReaderIndex => %s", byteBuf.getInt(0)));
        System.out.println(String.format("ReaderIndex => %s", byteBuf.readerIndex()));
        System.out.println(String.format("WriterIndex => %s", byteBuf.writerIndex()));
        System.out.println("==================================================================");
        byteBuf.writeInt(131);
        System.out.println(String.format("ReaderIndex => %s", byteBuf.getInt(0))); // get*不会一定readerIndex
        System.out.println(String.format("ReaderIndex => %s", byteBuf.readerIndex()));
        System.out.println(String.format("WriterIndex => %s", byteBuf.writerIndex()));
        byteBuf.readInt(); // read* or skip* 会移动readerIndex
        byteBuf.readInt();
        System.out.println("==================================================================");
        System.out.println(String.format("ReaderIndex => %s", byteBuf.getInt(0)));
        System.out.println(String.format("ReaderIndex => %s", byteBuf.readerIndex()));
        System.out.println(String.format("WriterIndex => %s", byteBuf.writerIndex()));
        byteBuf.discardReadBytes(); // 释放已读过的内容
        System.out.println("==================================================================");
        System.out.println(String.format("ReaderIndex => %s", byteBuf.getInt(0)));
        System.out.println(String.format("ReaderIndex => %s", byteBuf.readerIndex()));
        System.out.println(String.format("WriterIndex => %s", byteBuf.writerIndex()));
        byteBuf.readInt();
        byteBuf.readInt();
        byteBuf.readInt();
        byteBuf.readInt(); // 超出，会抛异常，IndexOutOfBoundsException
        ReferenceCountUtil.release(byteBuf);
    }

    /**
     * netty监控内存泄漏测试
     */
    public static void oofTest() {
        System.setProperty("io.netty.leakDetection.samplingInterval", "1");
        ResourceLeakDetector.setLevel(ResourceLeakDetector.Level.PARANOID);
        PooledByteBufAllocator allocator = PooledByteBufAllocator.DEFAULT;
        ByteBuf byteBuf = allocator.directBuffer(32);
        // 计数+1
        byteBuf.retain();
        byteBuf = null;
        System.gc();

        ByteBuf byteBuf1 = allocator.directBuffer(32);
        byteBuf1.readerIndex(byteBuf1.writerIndex());
    }
}
